<?php

namespace app\jigou\controller\qingdongams\customer;

use addons\qingdongams\model\Message;
use addons\qingdongams\model\Notice as NoticeModel;
use addons\qingdongams\model\NoticeRead;
use addons\qingdongams\model\ReceivablesPlan;
use addons\qingdongams\model\Record as RecordModel;
use addons\qingdongams\model\Workorder;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Contract;
use think\Db;
use think\Exception;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\ExamineRecord;

use addons\qingdongams\model\Record;

/**
 * 待办管理
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
class Need extends Base
{
    protected $relationSearch = true;

    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->type = array(
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'消息提醒',
                'text'=>'消息提醒',
            ),
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'公告',
                'text'=>'消息提醒',
            ),
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'今日需联系客户',
                'text'=>'消息提醒',
            ),
        );

        $this->assignconfig('typeList', $this->type);
    }
    /**
     * 待办列表
     */
    public function index(){

        //消息提醒
        $whereNew = [
            'status'=>0,
            'to_staff_id' => $this->_staff->id ,
            'relation_type'=>['not in','examine,discuss,sign,comment,leadspool_achieve,invoice,add_lead,customer,workorder_achieve,leads_tranfer,leads_move_pool']
        ];
        $news = Message::where($whereNew)->count();
        //公告
        $noticeid = NoticeModel::where([])->column('id');
        foreach($noticeid as $k=>$v){
            $read = NoticeRead::where(['notice_id'=>$v,'staff_id'=>$this->_staff->id])->find();
            if($read){
                unset($noticeid[$k]);
                continue;
            }
        }
        $notice = count($noticeid);
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $where['createtime'] = array(array('egt',strtotime($start)),array('elt',strtotime($end)));
        $whereR['next_time'] = array(array('egt',$start),array('elt',$end));
        //待线索跟进
        $whereLead['create_staff_id'] = $this->_staff->id;
        $whereLead['relation_type'] = 4;
        $whereLead['status'] = 0;
        $lead   = Record::where($whereLead)->where($whereR)->count();

        $whereCustomer['create_staff_id'] = $this->_staff->id;
        $whereCustomer['relation_type'] = 1;
        $whereCustomer['status'] = 0;
        $customer   = Record::where($whereCustomer)->where($whereR)->count();

        $whereBusiness['create_staff_id'] = $this->_staff->id;
        $whereBusiness['relation_type'] = 5;
        $whereBusiness['status'] = 0;
        $business   = Record::where($whereBusiness)->where($whereR)->count();

        $whereContract['create_staff_id'] = $this->_staff->id;
        $whereContract['relation_type'] = 3;
        $whereContract['status'] = 0;
        $contract   = Record::where($whereContract)->where($whereR)->count();


        //费用审核
        $consume = ExamineRecord::where([
            'relation_type'  => ExamineRecord::CONSUME_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();

        //待审核订单
        $examine = ExamineRecord::where([
            'relation_type'  => ExamineRecord::CONTRACT_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待审核回款
        $receivables = ExamineRecord::where([
            'relation_type'  => ExamineRecord::RECEIVABLES_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id,
        ])->count();
        //待审批办公
        $approval = ExamineRecord::where([
            'relation_type'  => ExamineRecord::APPROVAL_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id,
        ])->count();

        //业绩审核
        $achievement = ExamineRecord::where([
            'relation_type'  => ExamineRecord::ACHIEVEMENT_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();

        //待入库审批
        $partin = ExamineRecord::where([
            'relation_type'  => ExamineRecord::PARTS_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待报价审批
        $quote = ExamineRecord::where([
            'relation_type'  => ExamineRecord::QUOTE_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待处理工单
        $whereStaff = function ($query) {
            $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_id)");
        };
        $wheres['status']=array('in','0,1');
        $workorder = Workorder::where($whereStaff)->where($wheres)->where($where)->count();
        //待发票审批
        $invoice = ExamineRecord::where([
            'relation_type'  => ExamineRecord::INVOICE_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //即将到期的订单
        $starttime = date('Y-m-d 23:59:59');
        $endtime = date("Y-m-d 00:00:00", strtotime("-3 day"));
        $whereOver['order_staff_id'] =  array('in',Staff::getMyStaffIds());
        $whereOver['check_status'] = 2;
        $whereOver['end_time'] = array(array('egt',$endtime),array('elt',$starttime));
        $contract_over = Contract::where($whereOver)->count();
        $info = array(
            'customer'=>$customer,
            'contract'=>$contract,
            'lead'=>$lead,
            'consume'=>$consume,
            'news'=>$news,
            'examine'=>$examine,
            'receivables'=>$receivables,
            'approval'=>$approval,
            'notice'=>$notice,
            'achievement'=>$achievement,
            'business'=>$business,
            'partin'=>$partin,
            'quote'=>$quote,
            'workorder'=>$workorder,
            'invoice'=>$invoice,
            'contract_over'=>$contract_over,
        );
        $this->view->assign('row',$info);
        $this->assignconfig("info", ['time' => date('Y-m-d 00:00:00').' - '.date('Y-m-d 23:59:59')]);

        return $this->view->fetch();
    }
    /**
     * 获取通知数量
     */
    public function get_need_number(){
        //消息提醒
        $whereNew = ['status'=>0,'to_staff_id' => $this->_staff->id ,'relation_type'=>['not in','examine,discuss,sign,comment,leadspool_achieve,invoice,add_lead,customer,workorder_achieve,leads_tranfer,leads_move_pool']];
        $news = Message::where($whereNew)->count();
        //公告
        $noticeid = NoticeModel::where([])->column('id');
        foreach($noticeid as $k=>$v){
            $read = NoticeRead::where(['notice_id'=>$v,'staff_id'=>$this->_staff->id])->find();
            if($read){
                unset($noticeid[$k]);
                continue;
            }
        }
        $notice = count($noticeid);
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $where['createtime'] = array(array('egt',strtotime($start)),array('elt',strtotime($end)));
        $whereR['next_time'] = array(array('egt',$start),array('elt',$end));
        //待线索跟进
        $whereLead['create_staff_id'] = $this->_staff->id;
        $whereLead['relation_type'] = 4;
        $whereLead['status'] = 0;
        $lead   = Record::where($whereLead)->where($whereR)->count();

        $whereCustomer['create_staff_id'] = $this->_staff->id;
        $whereCustomer['relation_type'] = 1;
        $whereCustomer['status'] = 0;
        $customer   = Record::where($whereCustomer)->where($whereR)->count();

        $whereBusiness['create_staff_id'] = $this->_staff->id;
        $whereBusiness['relation_type'] = 5;
        $whereBusiness['status'] = 0;
        $business   = Record::where($whereBusiness)->where($whereR)->count();

        $whereContract['create_staff_id'] = $this->_staff->id;
        $whereContract['relation_type'] = 3;
        $whereContract['status'] = 0;
        $contract   = Record::where($whereContract)->where($whereR)->count();


        //费用审核
        $consume = ExamineRecord::where([
            'relation_type'  => ExamineRecord::CONSUME_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();

        //待审核订单
        $examine = ExamineRecord::where([
            'relation_type'  => ExamineRecord::CONTRACT_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待审核回款
        $receivables = ExamineRecord::where([
            'relation_type'  => ExamineRecord::RECEIVABLES_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id,
        ])->count();
        //待审批办公
        $approval = ExamineRecord::where([
            'relation_type'  => ExamineRecord::APPROVAL_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id,
        ])->count();

        //业绩审核
        $achievement = ExamineRecord::where([
            'relation_type'  => ExamineRecord::ACHIEVEMENT_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();

        //待入库审批
        $partin = ExamineRecord::where([
            'relation_type'  => ExamineRecord::PARTS_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待报价审批
        $quote = ExamineRecord::where([
            'relation_type'  => ExamineRecord::QUOTE_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //待处理工单
        $whereStaff = function ($query) {
            $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_id)");
        };
        $wheres['status']=array('in','0,1');
        $workorder = Workorder::where($whereStaff)->where($wheres)->where($where)->count();
    //待发票审批
        $invoice = ExamineRecord::where([
            'relation_type'  => ExamineRecord::INVOICE_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->_staff->id
        ])->count();
        //即将到期的订单
        $starttime = date('Y-m-d 23:59:59');
        $endtime = date("Y-m-d 00:00:00", strtotime("-3 day"));
        $whereOver['order_staff_id'] =  array('in',Staff::getMyStaffIds());
        $whereOver['check_status'] = 2;
        $whereOver['end_time'] = array(array('egt',$endtime),array('elt',$starttime));
        $contract_over = Contract::where($whereOver)->count();
        $info = array(
            'customer'=>$customer,
            'contract'=>$contract,
            'lead'=>$lead,
            'consume'=>$consume,
            'news'=>$news,
            'examine'=>$examine,
            'receivables'=>$receivables,
            'approval'=>$approval,
            'notice'=>$notice,
            'achievement'=>$achievement,
            'business'=>$business,
            'partin'=>$partin,
            'quote'=>$quote,
            'workorder'=>$workorder,
            'invoice'=>$invoice,
            'contract_over'=>$contract_over,
        );
        $number=array_sum(array_values($info));
        $info['number']=$number;
        $this->success('请求成功','',$info);
    }

    /**
     * 提醒消息
     */
    public function news()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = ['to_staff_id' => $this->_staff->id,'relation_type'=>['not in','examine,discuss,sign,comment,leadspool_achieve,invoice,add_lead,customer,workorder_achieve,leads_tranfer,leads_move_pool']];
            $list = Message::where($where)->where($wheres)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

            foreach($list as $k=>$v){

                $list[$k]['relation_name'] = Message::messageType($v['relation_type'],$v['relation_id']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 公告
     */
    public function notice()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            $list = NoticeModel::where($where)->order('id desc')->paginate($limit);
            foreach ($list as $k => $v) {
                $read = NoticeRead::where(['notice_id'=>$v['id'],'staff_id'=>$staff->id])->find();
                if($read){
                    unset($list[$k]);
                    continue;
                }
                $read_staff_ids = explode(',', $v['read_staff_ids']);
                $list[$k]['is_read']   = in_array($staff->id, $read_staff_ids)?0:1;
                $list[$k]['content'] = strip_tags(htmlspecialchars_decode($v['content']));
            }
            $arr = $list->items();
            array_multisort($arr,SORT_DESC);
            $result = array("total" => $list->total(), "rows" => $arr);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 待线索跟进记录列表
     */
    public function leads() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 4;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','leads'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待客户跟进记录列表
     */
    public function customer() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 1;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','customer'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待商机跟进记录列表
     */
    public function business() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 5;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','business'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待订单跟进记录列表
     */
    public function contract() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $this->_staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 3;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','contract'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待工单处理列表
     */
    public function workorder() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $whereStaff = function ($query) {
                $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                    ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_id)");
            };
            $wheres['status']=array('in','0,1');
            $list   = Workorder::where($where)->where($whereStaff)->where($wheres)->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
}